﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Jenzabar.Portal.Framework.Web.UI;
using Jenzabar.Portal.Framework;//Req For PortletViewBase
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using Jenzabar.Common.Globalization;
using Jenzabar.Common.Mail;
using Jenzabar.Portal.Framework.EmailLogging;
using ConfigSettings = Jenzabar.Common.Configuration.ConfigSettings;

namespace Portlet.AURoster
{
    public partial class Add_View : PortletViewBase
    {
        string gdate;
        protected void Page_Load(object sender, EventArgs e)
        {
            //txtArea.Attributes.Add("onkeyup", "return parea()");
            //txtPrefix.Attributes.Add("onkeyup", "return pprefix()");
            //txtSuffix.Attributes.Add("onkeyup", "return psuffix()");
            txtMM.Attributes.Add("onkeyup", "return dobMM()");
            txtDD.Attributes.Add("onkeyup", "return dobDD()");
            txtYY.Attributes.Add("onkeyup", "return dobYY()");
            lblCoach.Text = PortalUser.Current.FirstName + " " + PortalUser.Current.LastName;
            lblDate.Text = DateTime.Now.ToShortDateString();
            

            if (IsFirstLoad)
            {
                PopulateSport(ddTeam);
                ddTeam.Items.Add(new ListItem("", ""));
                ddTeam.SelectedValue = "";
            }
        }

        private void PopulateSport(DropDownList dd)
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("CUS_sp_AURoaster_PopulateSport", myConn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader rdr;

                try
                {
                    myConn.Open();
                    rdr = cmd.ExecuteReader();
                    dd.DataSource = rdr;
                    dd.DataValueField = "ATTRIBUTE_CDE";
                    dd.DataTextField = "ATTRIBUTE_DESC";
                    dd.DataBind();
                    rdr.Close();

                }
                catch (Exception ex)
                {
                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error retrieving Data. " + ex.Message);


                }
                finally
                {

                    myConn.Close();
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SaveAll();
                sendEmail();
                this.ParentPortlet.NextScreen("Default");

            }
        }

        private void sendEmail()
        {
             // Find Where the Submission Form e.g Mytest > Default Page > Email Agreement
            string strPortletID = this.ParentPortlet.ID.ToString();
            string strTabPagePortlet = string.Empty;
            string[] strParts = this.ParentPortlet.PortletDisplay.Portlet.ToString().Replace("{CN=" + this.ParentPortlet.PortletDisplay.Portlet.Name + ",", "").Replace(",CN=Portal,O=Jenzabar,C=US}", "").Replace(",OU=Pages", "").Split(',');
            for (int idx = strParts.Length; idx > 0; idx--)
            {
                strTabPagePortlet += strParts[idx - 1].Replace("CN=", "") + " > ";
            }
            strTabPagePortlet += this.ParentPortlet.Title;

            // This is the body of the Email Sent to campusSafety and Student
            // ' Form Submission<br>Where: {0}<br>When: {1}<br>Who: {2}:'  CUS_VEHICLE_REGISTRATION_MSG_RESULTS_BODY_INTRO
            string strResults = "<table border=0> <tr align= left ><th colspan=2>" +
                                    Globalizer.Format( "CUS_AURoster_MSG_RESULTS_BODY_INTRO"
                                   // "<table border=0 cellspacing=0 cellpadding=2><tr align= left ><td align= left colspan='2'><b>SECURITY QUESTION SUBMISSION</b></td></tr> <tr align= left ><td align= left>Where:</td><td align= left >{0}</td></tr> <tr align= left ><td align= left >When:</td><td>{1:D} {1:t}</td></tr> <tr align= left ><td align= left >Who:</td><td>{2}</td></tr><tr align= left ><td align= left colspan='2'><hr/></td></tr></table>" 
                                   ,
                                    strTabPagePortlet,
                                    System.DateTime.Now,
                                    PortalUser.Current.NameDetails.ToString()

                                    )
                                    +
                                    "</th></tr></table>"
                                    ;


            string strSubject = "AURoster - New Student submitted by Coach " + lblCoach.Text ;

            string strToAddress = "Laura.Watson@avila.edu"; //"Mallika.Ramaswamy@avila.edu"; //

            string strBody = String.Empty;
            string strFrom = PortalUser.Current.EmailAddress.ToString();
            string strValue = String.Empty;
            string strCC = "Mallika.Ramaswamy@avila.edu";//"IT@Avila.edu";
            strBody += "<table  >";
            strBody += "<tr ><th    align=left valign=middle > New Student Details </th></tr>";
            strBody += "<tr ><th    align=left valign=middle >Team: </th><td  align=left valign=middle >" + ddTeam.SelectedValue + "  </td> </tr> ";
            strBody += "<tr ><th    align=left valign=middle > ID# : </th><td  align=left valign=middle >" + txtSID.Text+ "  </td> </tr> ";
            strBody += "<tr ><th    align=left valign=middle >First Name: </th><td  align=left valign=middle >" + txtFirst.Text + "  </td> </tr> ";
            strBody += "<tr ><th    align=left valign=middle >Last Name: </th><td  align=left valign=middle >" + txtLast.Text + "  </td> </tr> ";


            strBody += "<tr > <th   align=left  > Status :</th><td   align=left  >" + rbStatus.SelectedValue + "  </td> </tr> ";
            strBody += "<tr > <th   align=left  > College or HS:  :</th><td   align=left  >" + txtHS.Text + "  </td> </tr> ";
            if (txtMM.Text.Trim() != "" && txtDD.Text != "" && txtYY.Text != "")
            {
                gdate = txtMM.Text.Trim() + "/" + txtDD.Text.Trim() + "/" + txtYY.Text.Trim();
                strBody += "<tr > <th   align=left  > HS GRAD Date:  :</th><td   align=left  >" + gdate + "  </td> </tr> ";
            }
            strBody += "<tr > <th   align=left  > Previous Seasons Competed:</th><td   align=left  >" + txtCompeted.Text + "  </td> </tr> ";

            strBody += "<tr > <th   align=left  > NAIA EC#:</th><td   align=left  >" +txtNAIA.Text + "  </td> </tr> ";
           
            strBody += " </table> ";
            //// Now send the results, or at least try to
            strResults += strBody;
            // filter out bad From address
            string strNoteReFailedSend = string.Empty;
            string strNoteReBadFromAddressConfig = String.Empty;
            bool blFromAddressWasGood = ((new ValidEmail(strFrom.Trim())).IsValid);
            //not good
            if (!blFromAddressWasGood)
            {
                strNoteReBadFromAddressConfig = Globalizer.GetGlobalizedString("CUS_SIMPLEFORM_MSG_BAD_FROM_ADDR_CONFIG") +
                    " " + strFrom;
                strFrom = ConfigSettings.Current.SmtpDefaultEmailAddress;
            }
            // send the message, but note if it failed
            try
            {
                //sending the email to ITService 
                if (!Email.CreateAndSendMailMessage(strFrom, strToAddress, strCC, strSubject, strResults))
                {
                    //strNoteReFailedSend += "Couldn't send to " + strToAddress + " from " + strFrom + " ";
                    strNoteReFailedSend += "Couldn't send to " + strFrom + " from " + strFrom + " ";
                }
            }
            catch (Exception ee)
            {
                strNoteReFailedSend += ee.Message + " (see Event Log for details) - Couldn't send to " + strToAddress + " from " + strFrom + " ";

                Jenzabar.Common.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(ee);
            }
            
           
       
        }

        private void SaveAll()
        {
            InsertCoach();
            InsertPlayer();
        }

        private void InsertPlayer()
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {

                try
                {
                    myConn.Open();

                    SqlCommand cmd = new SqlCommand("CUS_sp_AURoster_Player_Insert", myConn);
                    cmd.Parameters.Add("@cid", SqlDbType.VarChar, 10).Value = PortalUser.Current.HostID;
                    cmd.Parameters.Add("@team", SqlDbType.VarChar, 10).Value = ddTeam.SelectedValue;
                    cmd.Parameters.Add("@sid", SqlDbType.VarChar, 10).Value = txtSID.Text;
                    cmd.Parameters.Add("@first", SqlDbType.VarChar, 100).Value = txtFirst.Text;
                    cmd.Parameters.Add("@last", SqlDbType.VarChar, 100).Value = txtLast.Text;
                    cmd.Parameters.Add("@status", SqlDbType.VarChar, 100).Value = rbStatus.SelectedValue;
                  //  cmd.Parameters.Add("@ssn", SqlDbType.VarChar).Value = txtSSN1.Text + txtSSN2.Text + txtSSN3.Text.Trim();
                    cmd.Parameters.Add("@compete", SqlDbType.VarChar, 100).Value = Convert.ToInt32(txtCompeted.Text);
                    cmd.Parameters.Add("@hs", SqlDbType.VarChar, 100).Value = txtHS.Text;
                    if (txtMM.Text.Trim() != "" && txtDD.Text != "" && txtYY.Text != "")
                    {
                        gdate = txtMM.Text.Trim() + "/" + txtDD.Text.Trim() + "/" + txtYY.Text.Trim();
                        cmd.Parameters.Add("@gdate", SqlDbType.VarChar, 20).Value = gdate ;
                    }
                    else
                    {

                        cmd.Parameters.Add("@gdate", SqlDbType.VarChar, 20).Value = string.Empty;
                    }
                    cmd.Parameters.Add("@ec#", SqlDbType.VarChar, 10).Value = txtNAIA.Text;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();

                }
                catch (Exception ex)
                {


                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error Inserting Data Items: " + ex.Message);
                }
                finally
                {
                    // Close Connection
                    myConn.Close();
                }
            }

        }

        private void InsertCoach()
        {
            using (SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["NotepadConnectionString"].ConnectionString))
            {

                try
                {
                    myConn.Open();

                    SqlCommand cmd = new SqlCommand("CUS_sp_AURoster_Coach_Insert", myConn);
                    cmd.Parameters.Add("@cid", SqlDbType.VarChar, 10).Value = PortalUser.Current.HostID;
                    cmd.Parameters.Add("@coach", SqlDbType.VarChar, 100).Value = lblCoach.Text;
                   // cmd.Parameters.Add("@phone", SqlDbType.VarChar, 10).Value = txtArea.Text + txtPrefix.Text + txtSuffix.Text;
                    cmd.Parameters.Add("@team", SqlDbType.VarChar, 100).Value = ddTeam.SelectedValue;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();

                }
                catch (Exception ex)
                {


                    this.ParentPortlet.ShowFeedback(FeedbackType.Error, "Error Inserting Data Items: " + ex.Message);
                }
                finally
                {
                    // Close Connection
                    myConn.Close();
                }
            }
        }
    }
}